package com.findyou.dao.impl;

import com.findyou.dao.UserDao;
import com.findyou.entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * @Title: UserDaoImpl
 * @Author 贾金博
 * @Package com.findyou.dao.impl
 * @Date 2024/11/15 上午8:47
 * @description: 实现类
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private QueryRunner queryRunner;

    // 为了后面的注入 埋下伏笔
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public UserDaoImpl() {}

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) throws SQLException {
        // ? 表示的是占位符
        String sql = "select * from user where id = ?";
        // 返回的是 单个的 用的是 BeanHandler ,    后面这个id要替换占位符
        User user = queryRunner.query(sql, new BeanHandler<User>(User.class), id);
        return user;
    }

    /**
     * 查询全部的用户
     * @return
     */
    @Override
    public List<User> findAllUsers() throws SQLException {
        String sql = "select * from user";
        List<User> userList = queryRunner.query(sql, new BeanListHandler<User>(User.class));
        return userList;
    }

    /**
     * 插入用户
     * @param user
     */
    @Override
    public void insertUser(User user) throws SQLException {
        String sql = "insert into user (username) values(?)";
        queryRunner.update(sql, user.getUsername());
    }

    /**
     * 根据id删除用户
     * @param id
     */
    @Override
    public void deleteUser(int id) throws SQLException {
        String sql = "delete from user where id = ?";
        queryRunner.update(sql, id);
    }

    /**
     * 更新用户的信息
     * @param user
     */
    @Override
    public void updateUser(User user) throws SQLException {
        String sql = "update user set username = ? where id = ?";
        queryRunner.update(sql, user.getUsername(), user.getId());
    }

}
